package com.exam.api.common.utils;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.toolkit.LambdaUtils;
import com.baomidou.mybatisplus.core.toolkit.support.LambdaMeta;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import org.apache.ibatis.reflection.property.PropertyNamer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Optional;
import java.util.function.Function;

/**
 * @author iaa
 * @Description mybatis-plus工具类
 * @Date 2024/4/26 上午10:46
 */
public class BlueUtil {
    private static final Logger log = LoggerFactory.getLogger(BlueUtil.class);

    /**
     * 根据lambda方法引用获取属性名
     * @param func
     * @return
     * @param <T>
     */
    public static <T> String columnToString(SFunction<T, ?> func) {
        LambdaMeta extract = LambdaUtils.extract(func);
        // 根据LambdaMeta获取方法名,然后截取出属性名
        String implMethodName = extract.getImplMethodName();
        return PropertyNamer.methodToProperty(implMethodName);
    }


    /**
     * 获取属性名并转换为下划线
     * @param func
     * @return
     * @param <T>
     */
    public static <T> String columnToUnderline(SFunction<T, ?> func) {
        String fieldName = tryCatch(func, BlueUtil::columnToString);
        return Optional.ofNullable(fieldName).map(CharSequenceUtil::toUnderlineCase).orElse(CharSequenceUtil.EMPTY);
    }

    public static <T, R> R tryCatch(T t, Function<T, R> function) {
        TimeInterval timer = DateUtil.timer();
        R r = null;
        try {
            r = function.apply(t);
        } catch (Exception e) {
            log.error("内部方法Function调用异常,错误信息:{}", e.getMessage(), e);
        }
//        log.info("内部方法Function调用,耗时:{}ms", timer.interval());
        return r;
    }

    public static void main(String[] args) {
//        System.out.println("columnToUnderline: "+columnToUnderline(TblLesson::getBrowseNumbers));
//        System.out.println("columnToString: "+columnToString(TblLesson::getBrowseNumbers));
    }
}
